package org.example.linkedList;

import java.util.Arrays;

/**
 * @Auther: wangbw
 * @Date:2020/12/11
 * @Description: org.example.linkedList
 * @version: 1.0
 */
public class MergeSort {
    public static void main(String[] args) {
        int[] arr = new int[]{4, 5, 3, 2, 8};
        sort(arr);
        print(arr);
    }

    private static void sort(int[] arr) {
        int[] arrcopy = new int[arr.length];
        sort(arr, arrcopy, 0, arr.length - 1);
    }

    private static void sort(int[] arr, int[] arrCopy, int start, int end) {
        if (start >= end)
            return;
        int mid = start + (end - start) / 2;
        sort(arr, arrCopy, start, mid);
        sort(arr, arrCopy, mid + 1, end);
        merge(arr, arrCopy, start, end, mid);
    }

    private static void merge(int[] arr, int[] temp, int start, int end, int mid) {
        int i = start;
        int j = mid + 1;
        int index = start;
        for (int k = start; k <= end; k++) {
            temp[k] = arr[k];
        }
        while (index <= end) {
            System.out.println(index);
            if (i > mid) {
                arr[index] = temp[j++];
            } else if (j > end) {
                arr[index] = temp[i++];
            } else if (temp[i] <= temp[j]) {
                arr[index] = temp[i++];
            } else {
                arr[index] = temp[j++];
            }
            index++;
        }
    }

    private static void print(int[] arr) {
        System.out.println("result:" + Arrays.toString(arr));
    }
}
